package org.example.onlineEducation.config.security;

import org.example.onlineEducation.entity.User;
import org.example.onlineEducation.service.MenuService;
import org.example.onlineEducation.service.PermissionService;
import org.example.onlineEducation.service.UserService;
import org.example.onlineEducation.utils.LoginUser;
import org.example.onlineEducation.utils.MyGrantedAuthority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*
        实际使用时应从数据库中查出
         */
        User user = userService.selectByUsername(username);

        if(user == null)
            return null;

        List<String> strings = null;
        //防止权限列表为空
        if(user.getRoleId() == null){
            strings = Arrays.asList(new String[]{"/user/test"});
        }
        else {
            strings = new ArrayList<>();
            strings.add(String.valueOf(user.getRoleId()));
        }

        List<MyGrantedAuthority> authorities = new ArrayList<>();
        strings.forEach(str -> authorities.add(new MyGrantedAuthority(str)));
        System.out.println("\n\n---------------------------------- 分 割 线 ( 上 ）----------------------------------\n"
                +  authorities
                + "\n\n---------------------------------- 分 割 线 （ 下 ）----------------------------------");
        //设置user具有的权限
        LoginUser loginUser = new LoginUser(user);
        loginUser.setAuthorities(authorities);

        return loginUser;
    }
}
